import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from "@/components/Login.vue";
import Home from "@/components/Home.vue";
import UserView from "@/views/UserView.vue";
import GoodsView from "@/views/GoodsView.vue";
Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/login' // 默认重定向到登录页
  },
  {
    path: '/login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/home',
    component: Home,
    redirect:"/home/user_list",
    meta: { title: '主页' },
    children:[
      {path:'user_list',component:UserView},
      {path:'pro_list',component:GoodsView,},
     // {path:'article_list',component:ArticleView,meta:{title:'文章列表'}}
    ]
  }
];

const router = new VueRouter({
  routes
});

// 设置路由跳转前进行验证是否有 token
router.beforeEach((to, from, next) => {
  // 动态设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }

  // 如果访问的是登录页面，不需要验证 token
  if (to.path === '/login') {
    return next();
  }

  // 验证是否有 token
  const token = window.localStorage.getItem("token");

  if (token) {
    return next();
  } else {
    // 提示未登录
    Vue.prototype.$message.info("你还没有登录");
    return next("/login"); // 重定向到登录页面
  }
});

export default router;
